﻿<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>兼容IE8的输入框输入事件(原创)-jq22.com</title>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<style>
</style>
</head>
<body>
<link rel="stylesheet" href="https://www.jq22.com/jquery/bootstrap-3.3.4.css">
<div class="container">
    <div class="row">
        <div class="col-sm-6 col-sm-offset-3 col-xs-12" style="margin-top: 20px;">
            <div class="panel panel-primary">
                <div class="panel-heading">兼容IE8的输入框输入事件</div>
                <div class="panel-body">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="请输入内容" id="on-input">
                    </div>
                    <div class="alert alert-success" role="alert">
                        <span>当前输入内容：</span>
                        <span id="input-value"></span>
                    </div>
                    <div class="alert alert-danger" role="alert">
                        <strong>PS：用 IE8 测试一下</strong>
                    </div>
                </div>
                <div class="panel-footer">© 2019 helang.love@qq.com</div>
            </div>
        </div>
    </div>
</div>

<script>
/* 对象级别插件扩展 */
$.fn.extend({
    onInput: function(callback) {
        var el = $(this);
        /* 当前浏览器是否支持 oninput 事件 */
        if ("oninput" in el.get(0)) {
            el.on("input", function() {
                callback && callback($(this).val());
            });
        } else {
            el.keyup(function() {
                callback && callback($(this).val());
            });
            el.change(function() {
                callback && callback($(this).val());
            });
        }
    }
});

/* 插件调用 */
$("#on-input").onInput(function(value) {
    $("#input-value").html(value);
})
</script>

</body>
</html>
